local HealthBar = {} 

HealthBar.__index = HealthBar

setmetatable(HealthBar, {
	__call = function (cls, ...)
		return cls.new(...)
	end,
})

function HealthBar.new(xmlDoc, block, options)
	local self = setmetatable({}, HealthBar)
	self.text = options.text
	self.HealthMax = options.HealthMax
	self.HealthCurrent = options.HealthCurrent
	self.id = options.unit:GetId()
	self.unit = options.unit

	self.Frame = Apollo.LoadForm(xmlDoc, "BarTemplate", block.ContentList, self)
	self.Frame:FindChild("Text"):SetText(options.text)
	if options.icon then
		self.Frame:FindChild("Icon"):SetSprite(options.icon)
	end
	self.Frame:FindChild("RemainingOverlay"):SetMax(options.HealthMax)
	self.Frame:SetSprite("BarTextures_Fire")
	self.Frame:FindChild("RemainingOverlay"):SetFullSprite("BarTextures_Fire")
	return self
end

--------------------
-- BAR MANAGEMENT --
--------------------
function HealthBar:SetHealth(HealthCurrent,HealthMax)
	if HealthCurrent and HealthCurrent > 0 then
		self.HealthCurrent = HealthCurrent
	else
		self.HealthCurrent = 0
	end
	self.Frame:FindChild("RemainingOverlay"):SetProgress(self.HealthCurrent)
	
	if HealthMax and HealthMax > 0 then
		self.HealthMax = HealthMax
	else
		self.HealthMax = 1
	end
	self.Frame:FindChild("RemainingOverlay"):SetMax(self.HealthMax)
	
	self.Frame:FindChild("Timer"):SetText(string.format("%.1f", (self.HealthCurrent/self.HealthMax*100)) .. "%")
	local frameData = self.Frame:GetData()
	if frameData then
		frameData.current = self.HealthCurrent
	else
		frameData = {}
		frameData.current = self.HealthCurrent
	end
	self.Frame:SetData(frameData)
end
---------------------
-- /BAR MANAGEMENT --
---------------------

--------------------
-- GUI MANAGEMENT --
--------------------
function HealthBar:SetHeight(height)
	local left, top, right, bottom = self.Frame:GetAnchorOffsets()
	self.Frame:SetAnchorOffsets(left, top, right, top + height)

	local icon = self.Frame:FindChild("Icon")
	local iconHeight = icon:GetHeight()
	local left, top, right, bottom = icon:GetAnchorOffsets()
	icon:SetAnchorOffsets(left, top, left + iconHeight, bottom)

	local text = self.Frame:FindChild("Text")
	local left, top, right, bottom = text:GetAnchorOffsets()
	text:SetAnchorOffsets(iconHeight + 9, top, right, bottom)
end

function HealthBar:SetBGColor(color)
	self.Frame:SetBGColor(color)
end

function HealthBar:SetBarColor(color)
	test = self.Frame:FindChild("RemainingOverlay")
	self.Frame:FindChild("RemainingOverlay"):SetBarColor(color)
end
---------------------
-- /GUI MANAGEMENT --
---------------------

if _G["RaiderinoLibs"] == nil then
	_G["RaiderinoLibs"] = { }
end
_G["RaiderinoLibs"]["HealthBar"] = HealthBar